package com.xiaotao.test01.service;

import com.xiaotao.test01.entity.Result;
import com.xiaotao.test01.websocket.CustomerDeCoder;
import com.xiaotao.test01.websocket.CustomerEnCoder;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author xiaotao
 */
@Component
@Slf4j
@ServerEndpoint(value = "/websocket/{type}", encoders = {CustomerEnCoder.class},decoders = {CustomerDeCoder.class})
@RequiredArgsConstructor
public class WebSocket {

    // 连接数
    private static final AtomicInteger ONLINE_SESSION_CLIENT_COUNT = new AtomicInteger(0);

    // 客户端
    private static final Map<String, List<Session>> ONLINE_SESSION_CLIENT_MAP = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(@PathParam("type") String type, Session session) {
        log.debug("连接建立中 ==> type = {}", type);
        List<Session> sessions = ONLINE_SESSION_CLIENT_MAP.get(type);
        if (sessions == null) {
            List<Session> arrayList = new ArrayList<>();
            arrayList.add(session);
            ONLINE_SESSION_CLIENT_MAP.put(type,arrayList);
        }else {
            ONLINE_SESSION_CLIENT_MAP.get(type).add(session); 
        }
        //在线数加1
        ONLINE_SESSION_CLIENT_COUNT.incrementAndGet();
        log.debug("连接建立成功，当前在线数为：{}", ONLINE_SESSION_CLIENT_COUNT.get());
    }

    @OnClose
    public void onClose(@PathParam("type") String type,Session session) {
        ONLINE_SESSION_CLIENT_MAP.get(type).remove(session);
        ONLINE_SESSION_CLIENT_COUNT.decrementAndGet();
        log.debug("连接关闭成功，==> type = {}", type);
    }

    /**
     * 收到信息
     * @param result
     * @param session
     */
    @OnMessage
    public void onMessage(@PathParam("type") String type,Result result, Session session) {
        // 如果是心跳检测，就返回
        if (Objects.equals(result.getCode(), "201")) {
            this.sendHeart(session);
        }else {
            this.sendHandler(type,result,session);
        }
    }

//    public void sendMessage(String message,String uId) {
//        ONLINE_SESSION_CLIENT_MAP.forEach((onlineSid, toSession) -> {
//            // 排除掉自己
//            if (uId.equalsIgnoreCase(onlineSid)) {
//                log.info("服务端给客户端群发消息 ==> sid = {}, toSid = {}, message = {}", uId, onlineSid, message);
//                toSession.getAsyncRemote().sendText(message);
//            }
//        });
//    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("WebSocket发生错误，错误信息为：" + error.getMessage());
        error.printStackTrace();
    }

    private void sendHeart(Session session) {
        session.getAsyncRemote().sendObject(Result.health());
    }

    /**
     * 发送消息
     */
    private void sendHandler(String type, Result result, Session session) {
        List<Session> sessions;
        if ("server".equals(type)) {
            sessions = ONLINE_SESSION_CLIENT_MAP.get("client");
        }else {
            sessions = ONLINE_SESSION_CLIENT_MAP.get("server");
        }
        if (sessions != null) {
            for (Session item :sessions) {
                item.getAsyncRemote().sendObject(result);
            }
            log.info("客户端消息发送到服务端 ==>result = {}", result);
        }else {
            session.getAsyncRemote().sendObject(Result.error("server can not connect,please tell admin"));
            log.error("服务端不存在");
        }
    }

    public Integer getOnlineCount(){
        return ONLINE_SESSION_CLIENT_MAP.size();
    }

    public boolean getServerStatus(){
        List<Session> server = ONLINE_SESSION_CLIENT_MAP.get("server");
        return server != null && !server.isEmpty();
    }
}

